package com.tuanbiao.ui.plan;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.abiao.lib_utils.ViewUtils;
import com.hzjq.data.entity.PlanEntity;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.controllers.PlanController;
import com.tuanbiao.databinding.ActivityDetonatorPlanManageBinding;
import com.tuanbiao.dialog.BaseDialog;
import com.tuanbiao.dialog.InputDialog;
import com.tuanbiao.dialog.MessageDialog;
import com.tuanbiao.dialog.WaitDialog;
import com.tuanbiao.events.DetonatorRegisterEvent;
import com.tuanbiao.events.PlanEntityEvent;
import com.tuanbiao.models.PlanModel;
import com.tuanbiao.presenter.PlanManagePresenter;
import com.tuanbiao.ui.auth.AuthOnlineActivity;
import com.tuanbiao.ui.blast.BlastNettedActivity;
import com.tuanbiao.ui.plan.adapter.PlanAdapter;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.LibCollections;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/8 17:00
 */
public class PlanManageActivity extends BasePresenterActivity<PlanManagePresenter, ActivityDetonatorPlanManageBinding> implements PlanController.View {
    private WaitDialog.Builder checkDialog;
    private ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Timber.i(TAG + "#onActivityResult");
            if (result.getResultCode() == RESULT_OK) {
                mPresenter.refresh();
            }
        }
    });
    private boolean isEdit;
    private boolean isSelected;
    private PlanAdapter detonatorPlanAdapter;


    public static void start(Context context) {
        Intent starter = new Intent(context, PlanManageActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected ActivityDetonatorPlanManageBinding getBindingView() {
        return ActivityDetonatorPlanManageBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        initListener();

        binding.srlContent.setEnableLoadMore(false);
        binding.srlContent.setOnRefreshListener(refreshLayout -> mPresenter.refresh());
        detonatorPlanAdapter = new PlanAdapter();
        detonatorPlanAdapter.setListener(this::showStatistic);
        detonatorPlanAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            PlanEntity plan = (PlanEntity) adapter.getItem(position);
            if (null != plan) {
                plan.setSelect(!plan.isSelect());
                mPresenter.update(plan);
            }
        });
        detonatorPlanAdapter.addChildClickViewIds(R.id.ll_edit, R.id.ll_auth, R.id.ll_delete, R.id.tv_details,R.id.tv_share);
        detonatorPlanAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            PlanEntity plan = (PlanEntity) adapter.getItem(position);
            if (null != plan) {
                switch (view.getId()) {
                    case R.id.ll_edit:
                        showAddDialog(plan);
                        break;
                    case R.id.ll_auth:
                        mPresenter.auth(plan);
                        break;
                    case R.id.ll_delete:
                        showDeleteDialog(plan);
                        break;
                    case R.id.tv_details:
                        startDetonatorRegister(plan);
                        break;
                    case R.id.tv_share:
                        mPresenter.share(plan);
                        break;
                    default:
                        break;
                }
            }
        });
        binding.rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvContent.setAdapter(detonatorPlanAdapter);

    }

    private void initListener() {
        binding.tvRegister.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            mPresenter.startBlast();
        });
        binding.tvDelete.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            showDeleteDialog(detonatorPlanAdapter.getSelectData());
        });
        binding.tvSetting.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            launcher.launch(PlanSettingActivity.createIntent(getActivity()));
        });
        binding.ivToolbarBack.setOnClickListener(getBackListener());
        binding.tvManage.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            isEdit = !isEdit;
            binding.tvManage.setText(isEdit ? R.string.project_manage_sub_title_manage_cancel : R.string.project_manage_sub_title_manage);
            binding.tvDelete.setVisibility(isEdit ? View.VISIBLE : View.GONE);
            binding.tvMerge.setVisibility(isEdit ? View.VISIBLE : View.GONE);
            binding.tvRegister.setVisibility(isEdit ? View.GONE : View.VISIBLE);
        });
        binding.ivAdd.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            showAddDialog(null);
        });
        binding.ivSelect.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            Timber.i("onCheckedChanged:" + isSelected);
            isSelected = !isSelected;
            mPresenter.select(isSelected);
        });
        binding.tvMerge.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            showMergeDialog(detonatorPlanAdapter.getSelectData());
        });
    }


    @Override
    protected PlanManagePresenter createPresenter() {
        return new PlanManagePresenter(new PlanModel(), this);
    }

    @Override
    public void setPlantItems(List<PlanEntity> planList) {
        binding.srlContent.finishRefresh();
        if (LibCollections.isEmpty(planList)) {
            detonatorPlanAdapter.setEmptyView(ViewUtils.layoutId2View(R.layout.include_no_data));
        }
        detonatorPlanAdapter.setNewInstance(planList);
    }

    @Override
    public void onPlanChange(PlanEntity plan) {
        detonatorPlanAdapter.update(plan);
    }

    @Override
    public void onPlanDelete(PlanEntity plan) {
        showMessage("删除方案成功");
        detonatorPlanAdapter.remove(plan);
        if (LibCollections.isEmpty(detonatorPlanAdapter.getData())) {
            mPresenter.refresh();
        }
    }

    @Override
    public void onPlanSelectChange(boolean select) {
        if (select) detonatorPlanAdapter.selectAll();
        else detonatorPlanAdapter.unSelectAll();
    }

    @Override
    public void startDetonatorRegister(PlanEntity plan) {
        EventBus.getDefault().postSticky(new DetonatorRegisterEvent(plan));
        launcher.launch(DetonatorRegisterActivity.createIntent(getActivity()));
//        DetonatorRegisterActivity.start(getActivity());
    }

    @Override
    public void refresh() {
        binding.srlContent.autoRefresh();
    }

    @Override
    public void refreshFailed(String msg) {
        binding.srlContent.finishRefresh(false);
    }

    @Override
    public void showStatistic(int planCount, int detonatorCount, int noAuthDetonatorCount) {
        Timber.i(TAG + "#showStatistic#planCount:" + planCount);
        isSelected = planCount >= LibCollections.size(detonatorPlanAdapter.getData());
        binding.ivSelect.setImageResource(isSelected
                ? R.drawable.checkbox_checked_ic : R.drawable.compound_normal_ic);
        binding.tvSelectPlanCount.setText(getString(R.string.detonator_plan_manage_select_plan_count, planCount));
        binding.tvSelectDetonatorCount.setText(getString(R.string.detonator_plan_manage_select_detonator_count, detonatorCount));
        binding.tvNoAuthDetonatorCount.setText(getString(R.string.detonator_plan_manage_no_auth_detonator_count, noAuthDetonatorCount));
    }

    @Override
    public void startAuthOnline(PlanEntity plan) {
        EventBus.getDefault().postSticky(new PlanEntityEvent(plan));
        AuthOnlineActivity.start(getActivity());
    }

    @Override
    public void startBlast() {
        BlastNettedActivity.start(getActivity());
        killMyself();
    }

    @Override
    public void showCheckDialog() {
        if (null == checkDialog)
            checkDialog = new WaitDialog.Builder(getActivity()).setMessage("正在检测中");
        checkDialog.show();
    }

    @Override
    public void hideCheckDialog() {
        if (null != checkDialog && checkDialog.isShowing()) {
            checkDialog.dismiss();
        }
    }

    private void showDeleteDialog(PlanEntity plan) {
        new MessageDialog.Builder(getActivity())
                .setTitle("警告")
                .setMessage("确定要删除该方案吗？")
                .setListener(new MessageDialog.OnListener() {
                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        mPresenter.delete(plan);
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {

                    }
                })
                .show();
    }

    private void showDeleteDialog(List<PlanEntity> plans) {
        if (LibCollections.isEmpty(plans)) {
            showMessage("请选择要删除的方案");
            return;
        }
        new MessageDialog.Builder(getActivity())
                .setTitle("警告")
                .setMessage("确定要删除所选方案吗？")
                .setListener(new MessageDialog.OnListener() {
                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        mPresenter.delete(plans);
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {

                    }
                })
                .show();
    }

    private void showAddDialog(final PlanEntity planEntity) {
        boolean isAdd = planEntity == null;
        // 输入对话框
        new InputDialog.Builder(this)
                .setCanceledOnTouchOutside(false)
                // 标题可以不用填写
                .setTitle(isAdd ? R.string.common_add : R.string.common_edit)
                .setContent(isAdd ? "" : planEntity.getName())
                // 提示可以不用填写
                .setHint(R.string.detonator_plan_manage_add_hint)
                // 确定按钮文本
                .setConfirm(R.string.common_confirm)
                .setMaxLength(40)
                // 设置 null 表示不显示取消按钮
                .setCancel(R.string.common_cancel)
                // 设置点击按钮后不关闭对话框
                .setAutoDismiss(false)
                .setListener(new InputDialog.OnListener() {
                    @Override
                    public void onConfirm(BaseDialog dialog, String content) {
                        if (TextUtils.isEmpty(content)) {
                            showMessage(R.string.detonator_plan_manage_add_hint);
                            return;
                        }
                        PlanEntity newPlanEntity = planEntity;
                        if (null == newPlanEntity)
                            newPlanEntity = new PlanEntity();
                        newPlanEntity.setName(content);
                        if (isAdd) {
                            mPresenter.insert(newPlanEntity);
                        } else mPresenter.update(newPlanEntity);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private void showMergeDialog(List<PlanEntity> plans) {
        if (LibCollections.size(plans) < 2) {
            showMessage("请选择至少2个方案进行合并");
            return;
        }
        long count = 0;
        for (PlanEntity plan : plans) {
            count += plan.getCapCount();
        }
        if (count > mPresenter.getMaxCapCount()) {
            showMessage("合并最大数不能超过" + mPresenter.getMaxCapCount());
            return;
        }
        // 输入对话框
        new InputDialog.Builder(this)
                // 标题可以不用填写
                .setTitle("合并方案")
                .setCanceledOnTouchOutside(false)
                // 提示可以不用填写
                .setHint("请输入合并方案名称")
                // 确定按钮文本
                .setConfirm(R.string.common_confirm)
                // 设置 null 表示不显示取消按钮
                .setCancel(R.string.common_cancel)
                // 设置点击按钮后不关闭对话框
                .setAutoDismiss(false)
                .setListener(new InputDialog.OnListener() {
                    @Override
                    public void onConfirm(BaseDialog dialog, String content) {
                        if (TextUtils.isEmpty(content)) {
                            showMessage("请输入合并方案名称");
                            return;
                        }
                        mPresenter.merge(content, plans);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                    }
                })
                .show();
    }
}